package level

import (
	"encoding/binary"

	"gitee.com/xuender/oils/u32"
)

// NextSequence 序列.
func (p *Service) NextSequence(key []byte) uint32 {
	mu := p.getMutex(key)

	mu.Lock()
	defer mu.Unlock()

	seq := uint32(0)
	seqKey := []byte{ByteSeq}
	seqKey = append(seqKey, key...)

	if bs, err := p.DB.Get(seqKey, nil); err == nil {
		seq = binary.BigEndian.Uint32(bs)
	}

	seq++

	if err := p.DB.Put(seqKey, u32.Bytes(seq), nil); err != nil {
		panic(err)
	}

	return seq
}

// NextSequenceASC 下一个顺序Key.
func (p *Service) NextSequenceASC(key []byte) []byte {
	return KeyASCByUint32(key, p.NextSequence(key))
}

// NextSequenceDESC 下一个倒序Key.
func (p *Service) NextSequenceDESC(key []byte) []byte {
	return KeyDESCByUint32(key, p.NextSequence(key))
}
